import { ProLayoutProps } from '@ant-design/pro-components';
import { request } from '@umijs/max';

function getConfig<T>(name: string, url: string): Promise<T> {
  const cache = localStorage.getItem(name);
  if (cache) {
    const config: T = JSON.parse(cache);
    return Promise.resolve(config);
  } else {
    return request<T>(url)
      .then((config) => {
        localStorage.setItem(name, JSON.stringify(config));
        return config;
      });
  }
}

function getConfigUseFetch<T>(name: string, url: string): Promise<T> {
  const cache = localStorage.getItem(name);
  if (cache) {
    const config: T = JSON.parse(cache);
    return Promise.resolve(config);
  } else {
    return fetch(url)
      .then(resp => resp.text())
      .then(configData => {
        localStorage.setItem(name, configData);
        const config: T = JSON.parse(configData);
        return Promise.resolve(config);
      });
  }
}

export function getLayoutConfig(): Promise<ProLayoutProps> {
  return getConfig<ProLayoutProps>('LayoutConfig', '/config/layout.json');
}

export function getRoutesConfig(): Promise<Array<App.Route>> {
  return getConfig<Array<App.Route>>('RouteConfig', '/config/routes.json');
}

export function getMonitorConfig() {
  return getConfig<App.MonitorConfig>('MonitorConfig', '/config/monitor.json');
}

export function getMicroAppConfig() {
  return getConfigUseFetch<App.MicroAppConfig>('MicroAppConfig', '/config/microApp.json');
}